/**
 * Created by Administrator on 2017/6/6.
 */
/**
 * Created by Administrator on 2017/1/15.
 */

var config = require('./config');
var MJ = require('../MJ/MJ');
var MJRoom = require('../MJ/room').MJRoom;

var Const = require('./const');
var SubCode = require('../subCode');


exports.YZMJRoom = MJRoom.extend({

    init: function (rid, creator, msg) {
        this._super(rid, creator, msg);
        this.baoCard = 0;            //会儿牌
        this.huiP = 0;
        this._huiFB = this.getOption('HUIF') == 1;
        this.eightMeng = this.getOption('mengCardsNum') == 8;
        this.huIndex = 0;
        this._genZ = {
            isGenz: 0,
            players: {
                '1': 0,
                '2': 0,
                '3': 0,
                '4': 0
            }
        }; //跟庄
        this.mengNum = 0;
        this.mengCards = [];
        this.pickCards = [];
        this._turns = msg.turns;
        // this._turns = 0;                  // 总圈数
        this._curTurns = 1;             // 当前圈数
        this.setSaveReplay(true);
    },
    reset: function () {
        this.baoCard = 0;            //会儿牌
        this.huiP = 0;
        this.huIndex = 0;
        this._genZ = {
            isGenz: 0,
            players: {
                '1': 0,
                '2': 0,
                '3': 0,
                '4': 0
            }
        }; //跟庄
        this.mengNum = 0;
        this.mengCards = [];
        this.pickCards = [];
    },
    /******************************************************************
     * 重载的接口
     ******************************************************************/
    setGenz: function (index, card) {
        this._genZ.players[index] = card;
        this.checkGenz();
    },
    isFinalRound: function () {
        return this._curTurns > this._turns;
    },
    onDestroy: function () {
        this.sendToAgency("onRoomsChange", {
            "destroy": true,
            "id": this.rid(),
            "createTime": this.getCreateTime(),
            "options": this.getOptions(),
            "round": this._turns,
            "curRound": this._curTurns,
            "costMode": this.getCostMode(),
            "playerNum": this.getPlayerCount()
        });
    },
    checkGenz: function () {
        if (this._genZ.isGenz == 0) {
            var p1Card = this._genZ.players['1'];
            var p2Card = this._genZ.players['2'];
            var p3Card = this._genZ.players['3'];
            var p4Card = this._genZ.players['4'];

            if (p1Card && p2Card && p3Card && p4Card) {
                if (p1Card == p2Card && p2Card == p3Card && p3Card == p4Card) {
                    if (this._genZ.isGenz != -1)
                        this._genZ.isGenz = 1;
                } else {
                    this._genZ.isGenz = -1;
                }
            }
        }

    },
    getInfo: function () {
        var info = this._super();

        info.huiCard = this.baoCard;
        info.huiP = this.huiP;
        info.turns = this._turns;
        info.curTurns = this._curTurns;
        return info;
    },
    getHuiP: function () {
        return this.huiP;
    },
    getRoundInfo: function () {
        var info = this._super();
        info.curTurns = this._curTurns;
        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.turns = this._turns;
        info.curTurns = this._curTurns;
        info.huiCard = this.baoCard;
        info.huiP = this.huiP
        return info;
    },
    getSettlementInfo: function () {
        var info = this._super();
        // info.isHZ = this.isRoundHZ(); // 是否黄庄家
        // info.dealerIndex = this.getDealerIndex();
        // info.dealerLZ = this.getDealerLZ();
        info.mengCards = this.mengCards;
        info.mengNum = this.mengNum;
        info.pickCards = this.pickCards;
        return info;
    },
    onBeforeStartNewRound: function () {
        this._super();
        this.reset();
    },
    /**
     * 摸牌前处理
     * 剩余14张牌直接黄庄结算
     */
    onBeforeNewCard: function () {
        if (this._publicCards.getRemainNum() <= 14) {
            this.settlementCurRound(0);
        }
    },

    getRoomConfig: function () {
        var cfg = this._super();
        cfg.destroyWaitTime = 120;
        return cfg;
    },

    /**
     * 检查当前玩家的挂起任务
     */
    checkCurPlayHangupTask: function () {
        var player = this.getCurPlayer();
        var gangArray = player.checkGang();
        var ffArray = player.checkFF();
        if (gangArray.length > 0) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }
        if (ffArray.length > 0) {
            this._hangupTask.addTask(player.getIndex(), MJ.Task.CUSTOM, { "fengjian": ffArray })
        }
        if (player.lastFJorHRG) {
            player.lastFJorHRG = false;
            var huPattern = player.checkHu();
            if (huPattern != Const.Pattern.NONE) {
                var rules = [];
                // if (player.isFirstHand()) {
                //     if (player.getIndex() == this.getDealerIndex()) {
                //         rules.push(Const.ScoreRule.TH);
                //     }
                // }
                //杠上花
                // if (this.getCurGang()) {
                //     if (!room.getBaoCardNum(player)) {
                //         huPattern = Const.Pattern.WHGSKH
                //     } else {
                //         huPattern = Const.Pattern.GSKH;
                //     }
                //     //rules.push(Const.ScoreRule.WHGSH);
                // }
                var card = player.getLastCard() || player.getInitLastCard();
                this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
            }

        }


    },

    /**
     * 检查摸牌后玩家的挂起任务
     * 摸牌后玩家有杠、胡
     * 放箭、放风
     */
    checkNewCardHangupTask: function () {
        var player = this.getCurPlayer();
        var room = this;

        var huPattern = player.checkHu();
        if (huPattern != Const.Pattern.NONE) {
            var rules = [];
            // if (player.isFirstHand()) {
            //     if (player.getIndex() == this.getDealerIndex()) {
            //         rules.push(Const.ScoreRule.TH);
            //     }
            // }
            //杠上花
            if (this.getCurGang()) {
                if (!room.getBaoCardNum(player)) {
                    huPattern = Const.Pattern.WHGSKH
                } else {
                    huPattern = Const.Pattern.GSKH;
                }
                //rules.push(Const.ScoreRule.WHGSH);
            }
            var card = player.getLastCard() || player.getInitLastCard();
            this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
        }

        var ffarray = player.checkFF();
        var fjarray = player.checkFJ();

        var specialArray = ffarray.concat(fjarray);
        if (specialArray.length) {
            this._hangupTask.addTask(player.getIndex(), MJ.Task.CUSTOM, { "fengjian": specialArray })
        }

        var gangArray = player.checkGang();
        if (gangArray.length) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }

    },

    /**
     * 检查出牌后其它玩家的挂起任务
     * @param card 当前出的牌
     */
    checkPlayCardHangupTask: function (card) {
        var player = this.getCurPlayer();
        var curPlay = this.getCurPlay();

        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != curPlay) {
                if (ePlayer.checkPengWithCard(card)) {
                    this._hangupTask.addPengTask(eIndex, card, curPlay);
                }
                if (ePlayer.checkGangWithCard(card)) {
                    var gangTask;
                    if (card == this.getHuiP()) {
                        gangTask = { card: card, from: curPlay, gang: Const.Gang.HDIAN };
                    } else {
                        gangTask = { card: card, from: curPlay, gang: MJ.Gang.DIAN };
                    }

                    this._hangupTask.addGangTask(eIndex, [gangTask]);
                }
            }
        }.bind(this));
    },
    /**
     * 检查杠牌后的挂起任务
     * @param playerIndex
     * @param card
     */
    // checkGangHangupTask: function (playerIndex, card) {

    // },

    /**
     * 检查是否可抢杠
     * @param task
     * @param gangInfo
     */
    // checkGangTaskQG: function (task, gangInfo) {
    //     return false;
    // },

    /**
     * 检查杠后是否需要发牌
     * @param gangInfo
     */
    checkGangNewCard: function (gangInfo) {
        return true;
    },

    /**
     * 检查胡牌后是否可能结算
     */
    checkHuSettlement: function () {
        return true;
    },

    /**
     * 胡牌处理
     * @param task
     */
    onSettlementHuTask: function (task) {
        var playerIndex = task.playerIndex;
        var pattern = task.pattern;
        var card = task.card;
        var from = task.from;

        var huPlayer = this.getPlayerByIndex(playerIndex);
        huPlayer._stat.huCard = card;
        var isZM = (playerIndex == from); // 是否是自摸

        var mengObj = this.getMeng(huPlayer);
        var mengCards = mengObj.members;
        var mengNum = mengObj.num;
        var pickCards = this.getMengCards();
        console.log("pickcards")
        console.log(pickCards);
        this.mengNum = mengNum;
        this.mengCards = mengCards;
        this.pickCards = pickCards;
        if (isZM) {
            this.huIndex = playerIndex;
            var FB = 1;
            switch (this._getHuPattern(pattern)) {
                case Const.HuPattern.NORMAL:
                    FB = 1;
                    break;
                case Const.HuPattern.TWO:
                    FB = 2;
                    break;
                case Const.HuPattern.FOUR:
                    FB = 4;
                    break;
                case Const.HuPattern.EIGHT:
                    FB = 8;
                    break;
            }

            if (this.getHRD() && huPlayer._hundiao && card == this.getBaoCard() && pattern != Const.Pattern.HRGW) {
                FB *= 2;
            }
            // console.log("CountAll")
            // console.log(this.getHRD());
            // console.log(mengNum);
            // console.log(FB);
            logger.debug("before")
            this.enumPlayers(function (eIndex, ePlayer) {
                logger.debug(eIndex)
                console.log("roundanGang");
                console.log(ePlayer._stat.roundanGang);

                console.log("roundbaGang");
                console.log(ePlayer._stat.roundbaGang);

                console.log("ffCounts");
                console.log(ePlayer._stat.ffCounts);

                console.log("fjCounts");
                console.log(ePlayer._stat.fjCounts);
                console.log("dianGangSum");
                console.log(ePlayer.dianGangStatus);
            })
            logger.debug("before CountAll %j %d %d", this.getHRD(), mengNum, FB);
            this._CountAll(huPlayer, this.getHRD(), mengNum, FB);
            logger.debug("after")
            this.enumPlayers(function (eIndex, ePlayer) {
                logger.debug(eIndex)
                console.log("roundanGang");
                console.log(ePlayer._stat.roundanGang);

                console.log("roundbaGang");
                console.log(ePlayer._stat.roundbaGang);

                console.log("ffCounts");
                console.log(ePlayer._stat.ffCounts);

                console.log("fjCounts");
                console.log(ePlayer._stat.fjCounts);
                console.log("dianGangSum");
                console.log(ePlayer.dianGangStatus);
            })

            this.broadcastReplay("onPlayerHu", {
                playerIndex: playerIndex,
                card: card,
                from: from,
            });
        }
    },
    _countGenZ: function () {
        if (this._genZ.isGenz == 1) {
            this.enumPlayers(function (eIndex, ePlayer) {
                if (ePlayer.isDealer()) {
                    ePlayer.addgenZScore(-3);
                } else {
                    ePlayer.addgenZScore(1);
                }
            })
        }
    },

    //不是庄家胡牌、不是混吊翻倍
    _countStyle1: function (huPlayer, mengCount, huFB) {
        //杠分、放风、放箭
        this.enumPlayers(function (eIndex, ePlayer) {
            var anGangC = ePlayer._stat.roundanGang;
            var baGangC = ePlayer._stat.roundbaGang;
            var ffC = ePlayer._stat.ffCounts;
            var fjC = ePlayer._stat.fjCounts;
            ePlayer.addGangScore(anGangC * 2 * 3);
            ePlayer.addDianGangScore(baGangC * 3);
            ePlayer.addGangScore(ffC * 2 * 3);
            ePlayer.addGangScore(fjC * 3);

            var dianGangSum = ePlayer.dianGangStatus;
            ePlayer.addDianGangScore(dianGangSum * 3);


            // ePlayer.dianGangStatus.forEach(function (v) {
            //     ePlayer.addDianGangScore(1)
            //     this.getPlayerByIndex(v).addDianGangScore(-1);

            // }.bind(this));
            this.enumPlayers(function (eIndex2, ePlayer2) {
                if (eIndex2 != eIndex) {
                    ePlayer2.addGangScore(-anGangC * 2);
                    ePlayer2.addGangScore(-ffC * 2);
                    ePlayer2.addGangScore(-fjC);
                    ePlayer2.addDianGangScore(-dianGangSum);
                    ePlayer2.addDianGangScore(-baGangC);
                }
            });
            // this.enumPlayers(function (eIndex2, ePlayer2) {
            //     if (eIndex2 != eIndex) {
            //         ePlayer2.addDianGangScore(-baGangC);
            //     }
            // });
        }.bind(this));
        var sumMengScore = 0;
        var sumBaseScore = 0;
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != huPlayer.getIndex()) {
                if (ePlayer.isDealer()) {
                    ePlayer.addBaseScore(-4 * huFB);
                    sumBaseScore += 4 * huFB;
                    ePlayer.addMengScore(-mengCount);
                    sumMengScore += mengCount;
                } else {
                    ePlayer.addBaseScore(-2 * huFB);
                    sumBaseScore += 2 * huFB;
                    ePlayer.addMengScore(-mengCount);
                    sumMengScore += mengCount;
                }
            }
        });
        huPlayer.addBaseScore(sumBaseScore);
        huPlayer.addMengScore(sumMengScore);
    },
    //不是庄家胡牌、是混吊翻倍、胡牌者不是混吊
    _countStyle2: function (huPlayer, mengCount, huFB) {
        this._countStyle1(huPlayer, mengCount, huFB);
    },
    //不是庄家胡牌、是混吊翻倍、胡牌者是混吊
    _countStyle3: function (huPlayer, mengCount, huFB) {
        //杠分、放风、放箭
        this.enumPlayers(function (eIndex, ePlayer) {
            var anGangC = ePlayer._stat.roundanGang;
            var baGangC = ePlayer._stat.roundbaGang;
            var ffC = ePlayer._stat.ffCounts;
            var fjC = ePlayer._stat.fjCounts;
            var dianGangSum = ePlayer.dianGangStatus;
            if (eIndex == huPlayer.getIndex()) {

                ePlayer.addGangScore(anGangC * 2 * 3);
                ePlayer.addDianGangScore(baGangC * 3);
                ePlayer.addGangScore(ffC * 2 * 3);
                ePlayer.addGangScore(fjC * 3);
                //var dianGangSum = ePlayer.dianGangStatus.length;
                ePlayer.addDianGangScore(dianGangSum * 3);
                // ePlayer.dianGangStatus.forEach(function (v) {
                //     ePlayer.addDianGangScore(1 * huFB);
                //     this.getPlayerByIndex(v).addDianGangScore(-1 * huFB);

                // }.bind(this));
            } else {

                ePlayer.addGangScore(anGangC * 2 * 3);
                ePlayer.addDianGangScore(baGangC * 3);
                ePlayer.addGangScore(ffC * 2 * 3);
                ePlayer.addGangScore(fjC * 3);
                //var dianGangSum = ePlayer.dianGangStatus.length;
                ePlayer.addDianGangScore(dianGangSum * 3);
                // ePlayer.dianGangStatus.forEach(function (v) {
                //     ePlayer.addDianGangScore(1);
                //     this.getPlayerByIndex(v).addDianGangScore(-1);

                // }.bind(this));
            }
            this.enumPlayers(function (eIndex2, ePlayer2) {
                // if (eIndex2 != eIndex && eIndex == huPlayer.getIndex()) {
                //     ePlayer2.addGangScore(-anGangC * 2, 7);
                //     ePlayer2.addDianGangScore(-baGangC, 7);
                //     ePlayer2.addGangScore(-ffC * 2);
                //     ePlayer2.addGangScore(-fjC);
                //     //var dianGangSum = ePlayer2.dianGangStatus.length;
                //     ePlayer2.addDianGangScore(-dianGangSum * 3);
                //
                // } else
                if (eIndex2 != eIndex) {
                    ePlayer2.addGangScore(-anGangC * 2, 8);
                    ePlayer2.addDianGangScore(-baGangC, 7);
                    ePlayer2.addGangScore(-ffC * 2);
                    ePlayer2.addGangScore(-fjC);
                    //var dianGangSum = ePlayer2.dianGangStatus.length;
                    ePlayer2.addDianGangScore(-dianGangSum);
                }
            });
        }.bind(this));
        var sumMengScore = 0;
        var sumBaseScore = 0;
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != huPlayer.getIndex()) {
                if (ePlayer.isDealer()) {
                    ePlayer.addBaseScore(-4 * huFB);
                    sumBaseScore += 4 * huFB;
                    ePlayer.addMengScore(-mengCount);
                    sumMengScore += mengCount;
                } else {
                    ePlayer.addBaseScore(-2 * huFB);
                    sumBaseScore += 2 * huFB;
                    ePlayer.addMengScore(-mengCount);
                    sumMengScore += mengCount;
                }
            }
        });
        huPlayer.addBaseScore(sumBaseScore);
        huPlayer.addMengScore(sumMengScore);
    },
    //是庄家胡牌、不是混吊翻倍
    _countStyle4: function (huPlayer, mengCount, huFB) {
        //杠分、放风、放箭
        this.enumPlayers(function (eIndex, ePlayer) {
            var anGangC = ePlayer._stat.roundanGang;
            var baGangC = ePlayer._stat.roundbaGang;
            var ffC = ePlayer._stat.ffCounts;
            var fjC = ePlayer._stat.fjCounts;
            ePlayer.addGangScore(anGangC * 2 * 3, 9);
            ePlayer.addDianGangScore(baGangC * 3);
            ePlayer.addGangScore(ffC * 2 * 3);
            ePlayer.addGangScore(fjC * 3);
            var dianGangSum = ePlayer.dianGangStatus;
            ePlayer.addDianGangScore(dianGangSum * 3);
            // ePlayer.dianGangStatus.forEach(function (v) {
            //     ePlayer.addDianGangScore(1);
            //     this.getPlayerByIndex(v).addDianGangScore(-1);

            // }.bind(this));
            this.enumPlayers(function (eIndex2, ePlayer2) {
                if (eIndex2 != eIndex) {
                    ePlayer2.addGangScore(-anGangC * 2);
                    ePlayer2.addDianGangScore(-baGangC);
                    ePlayer2.addGangScore(-ffC * 2);
                    ePlayer2.addGangScore(-fjC);
                    ePlayer2.addDianGangScore(-dianGangSum);
                }
            });
        }.bind(this));
        var sumMengScore = 0;
        var sumBaseScore = 0;
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != huPlayer.getIndex()) {
                ePlayer.addBaseScore(-4 * huFB);
                sumBaseScore += 4 * huFB;
                ePlayer.addMengScore(-mengCount);
                sumMengScore += mengCount;

            }
        });
        huPlayer.addBaseScore(sumBaseScore);
        huPlayer.addMengScore(sumMengScore);
    },
    //是庄家胡牌、是混吊翻倍、胡牌者是混吊
    _countStyle5: function (huPlayer, mengCount, huFB) {
        this.enumPlayers(function (eIndex, ePlayer) {
            var anGangC = ePlayer._stat.roundanGang;
            var baGangC = ePlayer._stat.roundbaGang;
            var ffC = ePlayer._stat.ffCounts;
            var fjC = ePlayer._stat.fjCounts;
            var dianGangSum = ePlayer.dianGangStatus;
            // if (eIndex == huPlayer.getIndex()) {

            //     ePlayer.addGangScore(anGangC * 2 * 3);
            //     ePlayer.addDianGangScore(baGangC * 3);
            //     ePlayer.addGangScore(ffC * 2 * 3);
            //     ePlayer.addGangScore(fjC * 3);
            //     //var dianGangSum = ePlayer.dianGangStatus.length;
            //     ePlayer.addDianGangScore(dianGangSum * 3);
            //     // ePlayer.dianGangStatus.forEach(function (v) {
            //     //     ePlayer.addDianGangScore(1 * huFB)
            //     //     this.getPlayerByIndex(v).addDianGangScore(-1 * huFB);

            //     // }.bind(this));
            // } else 
            {
                ePlayer.addGangScore(anGangC * 2 * 3);
                ePlayer.addDianGangScore(baGangC * 3);
                ePlayer.addGangScore(ffC * 2 * 3);
                ePlayer.addGangScore(fjC * 3);
                //var dianGangSum = ePlayer.dianGangStatus.length;
                ePlayer.addDianGangScore(dianGangSum * 3);
                // ePlayer.dianGangStatus.forEach(function (v) {
                //     ePlayer.addDianGangScore(1);
                //     this.getPlayerByIndex(v).addDianGangScore(-1);

                // }.bind(this));
            }
            this.enumPlayers(function (eIndex2, ePlayer2) {
                // if (eIndex2 != eIndex && eIndex == huPlayer.getIndex()) {
                //     ePlayer2.addGangScore(-anGangC * 2);
                //     ePlayer2.addDianGangScore(-baGangC);
                //     ePlayer2.addGangScore(-ffC * 2);
                //     ePlayer2.addGangScore(-fjC);
                //     //
                //     ePlayer2.addDianGangScore(-dianGangSum);
                // } else 
                if (eIndex2 != eIndex) {
                    ePlayer2.addGangScore(-anGangC * 2);
                    ePlayer2.addDianGangScore(-baGangC);
                    ePlayer2.addGangScore(-ffC * 2);
                    ePlayer2.addGangScore(-fjC);
                    //var dianGangSum = ePlayer2.dianGangStatus.length;
                    ePlayer2.addDianGangScore(-dianGangSum);
                }
            });
        }.bind(this));
        var sumMengScore = 0;
        var sumBaseScore = 0;
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != huPlayer.getIndex()) {
                ePlayer.addBaseScore(-4 * huFB);
                sumBaseScore += 4 * huFB;
                ePlayer.addMengScore(-mengCount);
                sumMengScore += mengCount;

            }
        });
        huPlayer.addBaseScore(sumBaseScore);
        huPlayer.addMengScore(sumMengScore);
    },
    _CountAll: function (huPlayer, huiFB, mengCount, FB) {
        this._countGenZ();
        if (huPlayer.isDealer()) {
            if (huiFB) {
                if (huPlayer._hundiao) {
                    logger.debug("countAll hu01")

                    this._countStyle5(huPlayer, mengCount, FB * 2)
                } else {
                    logger.debug("countAll hu02")

                    this._countStyle4(huPlayer, mengCount, FB)
                }
            } else {
                logger.debug("countAll hu03")

                this._countStyle4(huPlayer, mengCount, FB)
            }
        } else {
            if (huiFB) {
                if (huPlayer._hundiao) {
                    logger.debug("countAll hu04")

                    this._countStyle3(huPlayer, mengCount, FB * 2)
                } else {
                    logger.debug("countAll hu05")

                    this._countStyle1(huPlayer, mengCount, FB)
                }
            } else {
                logger.debug("countAll hu06")

                this._countStyle1(huPlayer, mengCount, FB)
            }
        }
    },
    _getHuPattern: function (pattern) {
        var hupattern;
        switch (pattern) {
            case Const.Pattern.NORMAL:
            case Const.Pattern.PAIR7:
                hupattern = Const.HuPattern.ONE;
                break;
            case Const.Pattern.WHR:
            case Const.Pattern.HRGW:
            case Const.Pattern.SHR:
            case Const.Pattern.GSKH:
                hupattern = Const.HuPattern.TWO;
                break;
            case Const.Pattern.WHGSKH:
            case Const.Pattern.QPAIR7:
                hupattern = Const.HuPattern.FOUR;
                break;
            case Const.Pattern.HHPAIR7:
                hupattern = Const.HuPattern.EIGHT;
                break;
        }
        return hupattern;
    },
    onSettlement: function () {
        // this.enumPlayers(function (eIndex, ePlayer) {
        //     ePlayer.addRoundScore(ePlayer.getSumScore());
        // })


        if (this.isRoundHZ()) {
            //黄庄不换庄
            //this._dealerIndex = this.getNextIndex(this._dealerIndex);
        } else {
            // 计算新的庄家
            var oldDealerIndex = this.getDealerIndex();
            var newDealerIndex = oldDealerIndex;
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex == this.huIndex) {
                    newDealerIndex = eIndex;
                }
            }.bind(this));

            if (this._dealerIndex != newDealerIndex) {
                //this._dealerIndex = newDealerIndex;
                this._dealerIndex = this.getNextIndex(this._dealerIndex);
                this._dealerLZ = 1;

                if (this._dealerIndex == 1) {
                    this._curTurns++; // 重新切换回东风位时圈数+1

                    this.sendToAgency("onRoomsChange", {
                        "id": this.rid(),
                        "createTime": this.getCreateTime(),
                        "options": this.getOptions(),
                        "round": this._turns,
                        "curRound": this._curTurns,
                        "costMode": this.getCostMode(),
                        "playerNum": this.getPlayerCount()
                    });

                }
            } else {
                this._dealerLZ += 1;
            }
        }



    },
    dealHangupTaskGang: function (task) {

        logger.debug("room=%d onHangupTaskGang args=%j", this.rid(), task);


        var playerIndex = task.playerIndex;
        var fromIndex = task.from;
        var card = task.card;
        var gang = task.gang;

        var player = this.getPlayerByIndex(playerIndex);

        var gangInfo = player.gangCard(task);
        if (!gangInfo) {
            return;
        }

        var broadcastGangInfo = clone(gangInfo);
        broadcastGangInfo.playerIndex = playerIndex;
        this.broadcastReplay("onPlayerGangCard", broadcastGangInfo);

        player.setPassHu(false);
        this._changeCurPlay(playerIndex, MJ.Task.GANG);
        this.onAfterGangTask(player, card, task, gangInfo);


        if (this.checkGangNewCard(gangInfo)) { // 没有则发摸牌
            this._dealNewCard(player);
        } else {
            this._doCheckCurPlayHangupTask();
        }

    },
    //=====================================================
    //处理放箭放风
    onCustomHangupTask: function (player, tasks) {

        var playerIndex = tasks.playerIndex;

        if (player.isFF) {
            var task;
            tasks.fengjian.forEach(function (v) {
                if (v.type == Const.Type.FF) {
                    task = v;
                }
            });
            var FFinfo = player.FFCard(task);
            player.played3XCount += 1;
            player._stat.ffCounts += 1;
            player.isFF = false;

            var broadcastFFInfo = clone(FFinfo);
            broadcastFFInfo.playerIndex = playerIndex;
            this._changeCurPlay(playerIndex, MJ.Task.CUSTOM);
            this.broadcastReplay("onPlayerFFCard", broadcastFFInfo);
            this._dealNewCard(player);

        } else if (player.isFJ) {
            var task;
            tasks.fengjian.forEach(function (v) {
                if (v.type == Const.Type.FF) {
                    task = v;
                }
            });
            var FJinfo = player.FJCard(task);
            player.played3XCount += 1;
            player._stat.fjCounts += 1;
            player.isFJ = false;

            player.lastFJorHRG = true;

            var broadcastFJInfo = clone(FJinfo);
            broadcastFJInfo.playerIndex = playerIndex;
            this._changeCurPlay(playerIndex, MJ.Task.CUSTOM);
            this.broadcastReplay("onPlayerFJCard", broadcastFJInfo);
            logger.debug("room=%d sendHangupTask in=YZMJ.onCustomHangupTask.TaskFJ", this.rid());
            this._doCheckCurPlayHangupTask();
        }

    },
    _changeCurPlay: function (playerIndex, task, newCard) {
        var oldCurPlay = this.getCurPlay();
        logger.debug("room=%d index=%d changeCurPlay old=%d task=%d", this.rid(), playerIndex, oldCurPlay, task);

        this._curPlay = playerIndex;
        this._curTask = task;
        this._curGang = (task == MJ.Task.GANG || task == MJ.Task.CUSTOM) ? (this._curGang + 1) : 0;

        if (this.getCurPlay() != oldCurPlay) {
            this._sendCurPlay(newCard);
        }

        this.getCurPlayer().setWaitHandleTime(this.getNowTime());
    },
    onBeforePlayCard: function (player, msg, card) {

    },
    onPlayerEnter: function (player) {

        console.log('enter')
        console.log(this.getCreator())
        this.sendToAgency("onRoomsChange", {
            "id": this.rid(),
            "createTime": this.getCreateTime(),
            "options": this.getOptions(),
            "round": this._turns,
            "curRound": this._curTurns,
            "costMode": this.getCostMode(),
            "playerNum": this.getPlayerCount()
        });
    },
    onAfterPlayerQuitRoom: function (player) {
        //this._super(player);
        this.sendToAgency("onRoomsChange", {
            "id": this.rid(),
            "createTime": this.getCreateTime(),
            "options": this.getOptions(),
            "round": this._turns,
            "curRound": this._curTurns,
            "costMode": this.getCostMode(),
            "playerNum": this.getPlayerCount()
        })
    },
    onAfterPlayCard: function (player, card, playInfo) {
        this._super(player, card, playInfo);
        this.setGenz(player.getIndex(), card);
        player._hundiao = false;
        if (player._hundiao == false) {
            console.log("check kkkk hundiao ")
            console.log(player.getIndex());
            console.log(player.checkHunDiao())
            if (player.checkHunDiao()) {
                player._hundiao = true;
            }
        }

    },
    startPlay: function () {
        var dealer = this.getDealerIndex();
        this.enumPlayers(function (eIndex, ePlayer) {//循环检测是否有会儿吊的玩家
            if (eIndex != dealer) {
                if (ePlayer.checkHunDiao()) {
                    ePlayer._hundiao = true;
                }
            }
        }.bind(this));
        logger.debug("room=%d sendHangupTask in=YZMJ.startPlay", this.rid());
        this._sendHangupTask(this._startPlay);//发送挂起任务
    },

    _startPlay: function () {
        this._changeCurPlay(this.getDealerIndex());
        this._doCheckNewCardHangupTask();
    },


    onAfterStartNewRound: function () {
        this._super();
        this.setHRP();
        this.initPlayersHandCards();  //初始化玩家手牌
        this.startPlay();
    },
    setHRP: function () {
        var hrp = this.getRandomCard();
        if (hrp == MJ.ZI.HZ) {
            this.baoCard = MJ.ZI.FC;
        } else if (hrp == MJ.ZI.FC) {
            this.baoCard = MJ.ZI.BB;
        } else if (hrp == MJ.ZI.BB) {
            this.baoCard = MJ.ZI.HZ;
        } else if (hrp == MJ.ZI.DF) {
            this.baoCard = MJ.ZI.NF;
        } else if (hrp == MJ.ZI.NF) {
            this.baoCard = MJ.ZI.XF;
        } else if (hrp == MJ.ZI.XF) {
            this.baoCard = MJ.ZI.BF;
        } else if (hrp == MJ.ZI.BF) {
            this.baoCard = MJ.ZI.DF;
        } else {
            if (MJ.getPoint(hrp) == 9) {
                this.baoCard = hrp - 8;
            } else {
                this.baoCard = hrp + 1;
            }
        }
        this.huiP = hrp;
        //去除一张会儿皮
        this._publicCards.getCard(hrp);
        this.broadcastReplay("onGetHuier", { "huiP": hrp, "huiCard": this.baoCard })
    },
    onAfterGangTask: function (player, card, gangTask, gangInfo) {
        var gangType = gangInfo.gang;
        var target = gangInfo.targets;

        if (gangType == MJ.Gang.AN || gangType == MJ.Gang.ANS ||
            gangType == Const.Gang.HAN || gangType == Const.Gang.HANS) {
            player._stat.anGangCount += 1;
            player._stat.roundanGang += 1;

            //player.gangScore += 6;
            // target.forEach(function (v) {
            //     this.getPlayerByIndex(v).gangScore -= 2;
            // }.bind(this));
            //巴杠算暗杠？
        } else if (gangType == MJ.Gang.BA) {
            player._stat.roundbaGang += 1;
            player._stat.roundmingGang += 1;
        } else if (gangType == MJ.Gang.DIAN || gangType == Const.Gang.HDIAN) {
            //this.getPlayerByIndex(target[0]).gangScore -= 1;
            // if (!player.dianGangStatus[target[0]]) {
            //     player.dianGangStatus.push(target[0])
            //     player.dianGangStatus[target[0]] = 1;
            // } else {
            //     player.dianGangStatus[target[0]] += 1;
            // }
            player.dianGangStatus += 1;
            player._stat.roundmingGang += 1;
        }
        if (gangType != MJ.Gang.BA) {
            player.played3XCount += 1;
        }
        player._hundiao = false;
        if (player._hundiao == false) {
            console.log("check kkkk hundiao gang")
            console.log(player.getIndex());
            console.log(player.checkHunDiao())
            if (player.checkHunDiao()) {
                player._hundiao = true;
            }
        }

    },
    onAfterPengTask: function (player, card, pengTask) {
        player.played3XCount += 1;
    },
    //给玩家发牌后
    onAfterNewCard: function () {

    },
    //杠后能不能摸牌
    checkGangNewCard: function (gangInfo) {
        if (gangInfo.type) {
            return false
        }
        return true;
    },

    checkHuSettlement: function () {
        return true;
    },
    onCurRoundFinished: function () {
        this._super();
        this.broadcastReplay("onDealerChanged", {
            dealer: this._dealerIndex,
            dealerLZ: this._dealerLZ,
            curTurns: this._curTurns
        });
    },

    /******************************************************************
     * 消息处理
     ******************************************************************/
    handleFfTask: function (player, msg, callback) {
        player.isFF = true;
        this._hangupTask.submitTask(player.getIndex(), MJ.Task.CUSTOM);
        callback({});
        //this.broadcast("onPlayerFFCard", { "playerIndex": player.getIndex() })
    },
    handleFjTask: function (player, msg, callback) {
        player.isFJ = true;
        this._hangupTask.submitTask(player.getIndex(), MJ.Task.CUSTOM);
        //this.broadcast("onPlayerFJCard", { "playerIndex": player.getIndex() })
        callback({});
    },
    handleEnjoy: function (player, msg, callback) {
        msg.playerIndex = player.getIndex();
        this.broadcast("onRoomChat", msg);
        callback({});
    },

    /******************************************************************
     * 功能接口
     ******************************************************************/
    getMeng: function (player) {
        var num = 0;
        var mengMember = [];

        var testCards = [];
        this.getMengCards().forEach(function (v) {
            testCards.push(v);
            // if (v == this.getBaoCard()) {
            //     var times = player._handCards.getCardNum(v);

            //     if (times != 0) {
            //         num += times;
            //         //num += 1;
            //         mengMember.push(v)
            //     } else {
            //         num += 1;
            //         mengMember.push(v);
            //     }

            //     return;
            // } else 
            //{

            var times = player._handCards.getCardNum(v);

            if (times != 0) {
                num += times;
                //num += 1;
                mengMember.push(v)
            }
            //}
            for (var i = 0, l = player._pengCards.length; i < l; ++i) {
                if (v == player._pengCards[i]) {
                    num += 3;
                    //num += 1;
                    mengMember.push(v);

                }
            }
            if (v == MJ.ZI.BF || v == MJ.ZI.DF || v == MJ.ZI.NF || v == MJ.ZI.XF) {
                var times1 = player._stat.ffCounts;

                if (times1) {
                    num += times1;
                    //num += 1;
                    mengMember.push(v);

                }
            }
            if (v == MJ.ZI.BB || v == MJ.ZI.FC || v == MJ.ZI.HZ) {

                var times2 = player._stat.fjCounts;

                if (times2) {
                    num += times2;
                    //num += 1;
                    mengMember.push(v);

                }
            }
        }.bind(this));

        return {
            "num": num,
            "members": mengMember,
        };
    },
    //获得最后4张牌
    getMengCards: function () {
        return this.eightMeng ? this._publicCards.lookCards(8) : this._publicCards.lookCards(4);
    },
    //随机获取一张牌
    getRandomCard: function () {
        var index = ExNumber.rand(this._publicCards.cards.length - 1);
        var card = this._publicCards.cards[index];
        return card;
    },
    //获取玩家宝牌数量
    getBaoCardNum: function (player) {
        return player._handCards.getCardNum(this.baoCard);
    },
    //计算牌
    getBaoCard: function () {
        return this.baoCard;
    },
    getHRD: function () {
        return this.getOption('HUIF') == 2;
    },

});
